#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
		int top = 0;
		int right = matrix[0].size() - 1;
		int bottom = matrix.size() - 1;
		int left = 0;
		int sum = (right + 1) * (bottom + 1) - 1;
		int i = 0;
		vector<int> res(sum+1);
		while(i <= sum){
			for(int j = left; j <= right; ++j, ++i) res[i] = matrix[top][j];
			++top;
            if(i > sum) break; // 防止溢出
			for(int j = top; j <= bottom; ++j, ++i) res[i] = matrix[j][right];
			--right;
            if(i > sum) break;// 防止溢出
			for(int j = right; j >= left; --j, ++i) res[i] = matrix[bottom][j];
            bottom--;
            if(i > sum) break;// 防止溢出
			for(int j = bottom; j >= top; --j, ++i) res[i] = matrix[j][left];
			++left;
            if(i > sum) break;// 防止溢出
		}
		return res;
    }
};

int main(){
	Solution so;
	vector<vector<int>> matrix = {
		{1,2,3,4},
		{5,6,7,8}
		,{9,10,11,12}
		};
	auto res = so.spiralOrder(matrix);
	for(auto item : res){
		cout << item << ",";
	}
	cout << endl;
	return 0;
}